<template>
    <div class="app-container content-wrapper">
        <div class="filter-container">
            <el-form :model="listQuery" :inline="true" ref="filterForm" style="display: inline-block">
                <el-form-item prop="carFullNum" class="filter-item">
                    <el-input v-model="listQuery.carFullNum" placeholder="车牌号" style="width: 200px;"></el-input>
                </el-form-item>

                <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
                <el-button class="filter-item" type="primary" icon="mars-reset" @click="handleResetFilter">重置</el-button>
                <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="plus" @click="handleCreate()">添加</el-button>
            </el-form>
        </div>

        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">

            <el-table-column label="ID" width="65" align="center">
                <template slot-scope="scope"> {{scope.row.id}} </template>
            </el-table-column>

            <el-table-column label="车牌号" width="300px" align="center">
                <template slot-scope="scope"> {{scope.row.carFullNum}} </template>
            </el-table-column>

            <el-table-column label="车型" width="150px" align="center">
                <template slot-scope="scope"> {{scope.row.carName}} </template>
            </el-table-column>

            <el-table-column label="行驶证" width="150px" align="center">
                <template slot-scope="scope"> <el-button type="text" @click="showPic(scope.row.carDriverPic)">查看</el-button> </template>
            </el-table-column>

            <el-table-column label="保险单" width="150px" align="center">
                <template slot-scope="scope">
                    <el-button type="text" @click="showPic(scope.row.carSecurePic)">正面</el-button>
                    <el-button type="text" @click="showPic(scope.row.carSecurePic2)">副本</el-button>
                </template>
            </el-table-column>

            <el-table-column label="备注" align="center">
                <template slot-scope="scope"> {{scope.row.remarks}} </template>
            </el-table-column>

            <el-table-column label="操作" width="180px" align="center">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>

                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" size="tiny" @close="handleCloseDialog">
            <el-form :model="form" :rules="rules" ref="form" labelPosition="right" labelWidth="120px" style="width: 500px">
                <el-form-item label="车牌">
                    <el-select v-model="form.carArea" placeholder="区域" style="width: 100px">
                        <el-option
                                v-for="item in carAreaOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                    <el-select v-model="form.carCity" placeholder="城市" style="width: 100px">
                        <el-option
                                v-for="item in carCityOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                    <el-input v-model="form.carNum" style="width: 100px"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="carName">
                    <el-input v-model="form.carName"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="form.remarks">
                    </el-input>
                </el-form-item>
                <el-form-item label="上传行驶证">
                    <file-upload
                            class="el-button el-button--primary"
                            :post-action="postAction"
                            :size="1024 * 1024 * 10"
                            :multiple="false"
                            v-model="files1"
                            @input-filter="inputFilter1"
                            @input-file="inputFile1"
                            ref="upload1">
                        <i class="el-icon-mars-add"></i>
                        选择图片
                    </file-upload>
                    <ul>
                        <li v-for="(file, index) in files1" :key="file.id">
                            <span>{{file.name}}</span> -
                            <span>{{file.size | formatSize}}</span> -
                            <span v-if="file.error">{{file.error}}</span>
                            <span v-else-if="file.success" style="color: green">上传成功</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else></span>
                            <div>
                                <img v-if="file.thumb" :src="file.thumb" width="40" height="auto" />
                            </div>
                        </li>
                    </ul>
                    <img v-if="files1.length == 0" :src="form.carDriverPic" width="40" height="auto" />
                </el-form-item>

                <el-form-item label="上传保险单">
                    <file-upload
                            class="el-button el-button--primary"
                            :post-action="postAction"
                            :size="1024 * 1024 * 10"
                            :multiple="false"
                            v-model="files2"
                            @input-filter="inputFilter2"
                            @input-file="inputFile2"
                            ref="upload2">
                        <i class="el-icon-mars-add"></i>
                        选择图片
                    </file-upload>
                    <ul>
                        <li v-for="(file, index) in files2" :key="file.id">
                            <span>{{file.name}}</span> -
                            <span>{{file.size | formatSize}}</span> -
                            <span v-if="file.error">{{file.error}}</span>
                            <span v-else-if="file.success" style="color: green">上传成功</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else></span>
                            <div>
                                <img v-if="file.thumb" :src="file.thumb" width="40" height="auto" />
                            </div>
                        </li>
                    </ul>
                    <img v-if="files2.length == 0" :src="form.carSecurePic" width="40" height="auto" />
                </el-form-item>

                <el-form-item label="上传保险单副本">
                    <file-upload
                            class="el-button el-button--primary"
                            :post-action="postAction"
                            :size="1024 * 1024 * 10"
                            :multiple="false"
                            v-model="files3"
                            @input-filter="inputFilter3"
                            @input-file="inputFile3"
                            ref="upload3">
                        <i class="el-icon-mars-add"></i>
                        选择图片
                    </file-upload>
                    <ul>
                        <li v-for="(file, index) in files2" :key="file.id">
                            <span>{{file.name}}</span> -
                            <span>{{file.size | formatSize}}</span> -
                            <span v-if="file.error">{{file.error}}</span>
                            <span v-else-if="file.success" style="color: green">上传成功</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else-if="file.active" style="color: red"><i class="el-icon-loading"></i> 上传中</span>
                            <span v-else></span>
                            <div>
                                <img v-if="file.thumb" :src="file.thumb" width="40" height="auto" />
                            </div>
                        </li>
                    </ul>
                    <img v-if="files2.length == 0" :src="form.carSecurePic2" width="40" height="auto" />
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import FileUpload from 'vue-upload-component'
    import fetch from '@/utils/fetch'
    import { created, deleted, updated, fetchObject, fetchList, uploadUrl } from '@/api/tukuan/manager'

    const carAreaOptions = [
        {label: '粤', key: '粤'},
        {label: '京', key: '京'},
        {label: '辽', key: '辽'}
    ]
    const carCityOptions = [
        {label: 'A', key: 'A'},
        {label: 'B', key: 'B'},
        {label: 'C', key: 'C'},
        {label: 'D', key: 'D'},
        {label: 'E', key: 'E'},
        {label: 'F', key: 'F'},
        {label: 'G', key: 'G'},
        {label: 'H', key: 'H'},
        {label: 'I', key: 'I'},
        {label: 'J', key: 'J'},
        {label: 'K', key: 'K'},
        {label: 'L', key: 'L'},
        {label: 'M', key: 'M'},
        {label: 'N', key: 'N'},
        {label: 'O', key: 'O'},
        {label: 'P', key: 'P'},
        {label: 'Q', key: 'Q'},
        {label: 'R', key: 'R'},
        {label: 'S', key: 'S'},
        {label: 'T', key: 'T'},
        {label: 'U', key: 'U'},
        {label: 'V', key: 'V'},
        {label: 'W', key: 'W'},
        {label: 'X', key: 'X'},
        {label: 'Y', key: 'Y'},
        {label: 'Z', key: 'Z'}
    ]

    export default {
        name: 'app',
        data() {
            return {
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    page: 1,
                    rows: 10,
                    carNum: undefined,
                    carName: undefined,
                    orderBy: 'create_time desc'
                },
                carAreaOptions,
                carCityOptions,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '编辑',
                    create: '添加'
                },
                form: {
                    carArea: '',
                    carCity: '',
                    carNum: '',
                    carName: '',
                    carDriverPic: '',
                    carSecurePic: '',
                    carSecurePic2: '',
                    remarks: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入应用名称', trigger: 'blur' }
                    ],
                    code: [
                        { required: true, message: '请输入唯一表示', trigger: 'blur' }
                    ]
                },

                files1: [],
                files2: [],
                files3: [],
                uploadAuto: true,
                postAction: uploadUrl
            }
        },
        components: {
            FileUpload
        },
        created() {
            this.getList()
        },
        filters: {
            statusFilter(status) {
                const statusArray = ['正常', '锁定']
                return statusArray[status?--status:'']
            },
            statusTagFilter(status) {
                const statusArray = ['success', 'danger']
                return statusArray[status?--status:'']
            }
        },
        methods: {
            inputFilter1(newFile, oldFile, prevent) {
                // 添加文件前
                //console.log('添加文件前')
                // 过滤系统文件 和隐藏文件
                if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                    return prevent()
                }
                // 过滤 php html js 文件
                if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                    return prevent()
                }

                if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                    // 创建 blob 字段
                    newFile.blob = ''
                    let URL = window.URL || window.webkitURL
                    if (URL && URL.createObjectURL) {
                        newFile.blob = URL.createObjectURL(newFile.file)
                    }
                    // 缩略图
                    newFile.thumb = ''
                    if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                        newFile.thumb = newFile.blob
                    }
                }
            },

            inputFile1(newFile, oldFile) {
                if (newFile && !oldFile) {
                    //console.log('add', newFile)
                }
                if (newFile && oldFile) {
                    //console.log('update', newFile)
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress')
                    }
                    if (newFile.error && !oldFile.error) {
                        console.log('上传发生错误')
                    }
                    if (newFile.success && !oldFile.success) {
                        //console.log('success')
                        if(this.files1[0].response.status) {
                            this.form.carDriverPic = this.files1[0].response.data.fileUrl
                        }

                    }
                }
                if (!newFile && oldFile) {
                    //console.log('remove', oldFile)
                }
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload1.active) {
                        this.$refs.upload1.active = true
                    }
                }
            },

            inputFilter2(newFile, oldFile, prevent) {
                // 添加文件前
                //onsole.log('添加文件前')
                // 过滤系统文件 和隐藏文件
                if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                    return prevent()
                }
                // 过滤 php html js 文件
                if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                    return prevent()
                }

                if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                    // 创建 blob 字段
                    newFile.blob = ''
                    let URL = window.URL || window.webkitURL
                    if (URL && URL.createObjectURL) {
                        newFile.blob = URL.createObjectURL(newFile.file)
                    }
                    // 缩略图
                    newFile.thumb = ''
                    if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                        newFile.thumb = newFile.blob
                    }
                }
            },

            inputFile2(newFile, oldFile) {
                if (newFile && !oldFile) {
                    //console.log('add', newFile)
                }
                if (newFile && oldFile) {
                    //console.log('update', newFile)
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress')
                    }
                    if (newFile.error && !oldFile.error) {
                        console.log('上传发生错误')
                    }
                    if (newFile.success && !oldFile.success) {
                        //console.log('success')
                        if(this.files2[0].response.status) {
                            this.form.carSecurePic = this.files2[0].response.data.fileUrl
                        }
                    }
                }
                if (!newFile && oldFile) {
                    //console.log('remove', oldFile)
                }
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload2.active) {
                        this.$refs.upload2.active = true
                    }
                }
            },

            inputFilter3(newFile, oldFile, prevent) {
                // 添加文件前
                //onsole.log('添加文件前')
                // 过滤系统文件 和隐藏文件
                if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                    return prevent()
                }
                // 过滤 php html js 文件
                if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                    return prevent()
                }

                if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                    // 创建 blob 字段
                    newFile.blob = ''
                    let URL = window.URL || window.webkitURL
                    if (URL && URL.createObjectURL) {
                        newFile.blob = URL.createObjectURL(newFile.file)
                    }
                    // 缩略图
                    newFile.thumb = ''
                    if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                        newFile.thumb = newFile.blob
                    }
                }
            },

            inputFile3(newFile, oldFile) {
                if (newFile && !oldFile) {
                    //console.log('add', newFile)
                }
                if (newFile && oldFile) {
                    //console.log('update', newFile)
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress')
                    }
                    if (newFile.error && !oldFile.error) {
                        console.log('上传发生错误')
                    }
                    if (newFile.success && !oldFile.success) {
                        //console.log('success')
                        if(this.files3[0].response.status) {
                            this.form.carSecurePic2 = this.files3[0].response.data.fileUrl
                        }
                    }
                }
                if (!newFile && oldFile) {
                    //console.log('remove', oldFile)
                }
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload3.active) {
                        this.$refs.upload3.active = true
                    }
                }
            },

            showPic(picUrl) {
                window.open(picUrl)
            },
            getList() {
                this.listLoading = true
                fetchList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch((error)=>{
                    console.log(error)
                    this.listLoading = false
                })
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleResetFilter() {
                this.$refs.filterForm.resetFields()
                this.getList()
            },
            handleCreate() {
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {
                this.dialogStatus = 'update'

                fetchObject(row.id).then(response => {
                    this.dialogFormVisible = true
                    this.form = Object.assign({}, response.data)
                })
            },
            handleDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            create() {
                if(this.files1.length > 0 && !this.files1[0].success) {
                    this.$notify({
                        title: '提示', message: '文件上传中，上传完成后再提交',
                        type: 'error', duration: 2000
                    })
                    return
                }
                if(this.files2.length > 0 && !this.files2[0].success) {
                    this.$notify({
                        title: '提示', message: '文件上传中，上传完成后再提交',
                        type: 'error', duration: 2000
                    })
                    return
                }
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        created(this.form).then(response => {
                            if (response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })

            },
            update() {
                if(this.files1.length > 0 && !this.files1[0].success) {
                    this.$notify({
                        title: '提示', message: '文件上传中，上传完成后再提交',
                        type: 'error', duration: 2000
                    })
                    return
                }
                if(this.files2.length > 0 && !this.files2[0].success) {
                    this.$notify({
                        title: '提示', message: '文件上传中，上传完成后再提交',
                        type: 'error', duration: 2000
                    })
                    return
                }
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogFormVisible = false
                        })
                    }
                })
            },
            resetForm() {
                this.$refs['form'].resetFields()
                this.files = []
                this.form = {
                    carArea: '',
                    carCity: '',
                    carNum: '',
                    carName: '',
                    carDriverPic: '',
                    remarks: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>